package com.highspeed.bdk.socket.client;

import com.highspeed.bdk.gateway.Util;
import com.highspeed.bdk.gateway.entity.LuckHeader;
import com.highspeed.bdk.gateway.entity.LuckMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        LuckMessage luckMessage = (LuckMessage)msg;
        LuckHeader luckHeader = luckMessage.getLuckHeader();
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        String docRoot = classpath.replaceAll("WEB-INF/classes/", "fbdata");
        StringBuffer filePath = new StringBuffer(docRoot);
        filePath.append("/");
        filePath.append(luckHeader.getFbOperType());
        filePath.append("/");

        StringBuffer fileName =new StringBuffer(luckHeader.getReqpacketId());
        fileName.append(".txt");
        Util.createFile(filePath.toString(),fileName.toString());
        filePath.append(fileName);
        try {
            FileOutputStream fileOutputStream =new FileOutputStream(new File(filePath.toString()));
            fileOutputStream.write(luckMessage.getContent());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("client接收到服务器返回的消息:" +   ((LuckMessage)msg).getContent());

    }
}  